package com.example.im.core.listener;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import com.example.im.constant.Constant;
import com.example.im.core.service.SocketIOService;
import com.example.im.core.vo.ReceiveMsg;
import com.example.im.core.vo.SendMsgCallback;
import com.example.im.core.vo.SendMsgCallbackInfo;
import com.example.im.util.AppContext;
import com.example.im.util.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * 对话事件监听器
 */
public class DialogueEventListener implements DataListener<ReceiveMsg> {

	private final Logger LOG = LoggerFactory.getLogger(DialogueEventListener.class);

	
	@Override
	public void onData(SocketIOClient client, ReceiveMsg data, AckRequest ackSender) throws Exception {
		//随机生成消息id
		String msgId = UUID.randomUUID().toString();
    	data.getData().setMsgId(msgId);

    	//在web Server容器中，无论是Servlet，Filter，还是Listener都不是Spring容器管理，无法在这些类中直接使用Spring注解的方式来注入我们需要的对象
    	SocketIOService socketIOService = AppContext.getContext().getBean(SocketIOService.class);
    	socketIOService.sendMsgSupportCluster(data, Constant.EVENT.DIALOGUE);
    	
		LOG.info("客户端(from)：{}，服务端IP(from)：{}，客户端(to)：{}，发送内容：{}", data.getData().getFrom().getId(), IPUtil.getHostIp(), data.getData().getTo().getId(), data.getData().getContent());
    	
		//回调客户端，即响应客户端
        this.sendAckData(data, ackSender, msgId);
	}

    /**
     * 回调客户端，即响应客户端
     * @param data
     * @param ackSender
     * @param msgId
     */
	private void sendAckData(ReceiveMsg data, AckRequest ackSender, String msgId) {
		//组装客户端接收的回调数据
		SendMsgCallback sendMsgCallback = new SendMsgCallback();
		sendMsgCallback.setType(Constant.OperateType.JOIN_CUSTOMER);
		SendMsgCallbackInfo sendMsgCallbackInfo = new SendMsgCallbackInfo();
		sendMsgCallbackInfo.setMsgId(msgId);
		sendMsgCallbackInfo.setMsgType(data.getData().getMsgType());
		sendMsgCallbackInfo.setSendTime(System.currentTimeMillis());
		sendMsgCallbackInfo.setReceiveTime(System.currentTimeMillis());
		sendMsgCallback.setData(sendMsgCallbackInfo);
		//回调客户端函数
		ackSender.sendAckData(sendMsgCallback);
		LOG.info("回调客户端，内容：{}", sendMsgCallback.toString());
	}

}
